package com.castle.fortress.admin.study.course.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.study.course.dto.StudyCoursewareDto;
import com.castle.fortress.admin.study.course.entity.StudyCoursewareEntity;
import com.castle.fortress.admin.study.course.mapper.StudyCoursewareMapper;
import com.castle.fortress.admin.study.course.service.StudyCoursewareService;
import com.castle.fortress.admin.system.dto.ConfigApiDto;
import com.castle.fortress.admin.system.service.ConfigApiService;
import com.castle.fortress.admin.utils.BizCommonUtil;
import com.castle.fortress.admin.utils.PdfUtils;
import com.castle.fortress.common.enums.CoursewareTypeEnum;
import com.castle.fortress.common.enums.FileSuffixEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课件管理 服务实现类
 *
 * @author castle
 * @since 2023-01-30
 */
@Service
public class StudyCoursewareServiceImpl extends ServiceImpl<StudyCoursewareMapper, StudyCoursewareEntity> implements StudyCoursewareService {
    @Autowired
    private PdfUtils pdfUtils;
    @Autowired
    private ConfigApiService configApiService;

    /**
     * 获取查询条件
     *
     * @param studyCoursewareDto
     * @return
     */
    public QueryWrapper<StudyCoursewareEntity> getWrapper(StudyCoursewareDto studyCoursewareDto) {
        QueryWrapper<StudyCoursewareEntity> wrapper = new QueryWrapper();
        if (studyCoursewareDto != null) {
            StudyCoursewareEntity studyCoursewareEntity = ConvertUtil.transformObj(studyCoursewareDto, StudyCoursewareEntity.class);
            wrapper.eq("1", "1");
            wrapper.eq(studyCoursewareEntity.getCoursewareType() != null, "courseware_type", studyCoursewareEntity.getCoursewareType());
            wrapper.like(StrUtil.isNotEmpty(studyCoursewareEntity.getCoursewareName()), "courseware_name", studyCoursewareEntity.getCoursewareName());
            wrapper.like(studyCoursewareEntity.getIsDownload() != null, "is_download", studyCoursewareEntity.getIsDownload());
            wrapper.last(studyCoursewareEntity.getClassifyId() != null, "AND classify_id in (" +
                    "                SELECT DISTINCT id FROM study_course_classify WHERE id= " + studyCoursewareEntity.getClassifyId() + " or parents like concat('%'," + studyCoursewareEntity.getClassifyId() + ",'%')\n" +
                    "                )" +
                    "ORDER BY create_time");
        } else {
            wrapper.orderByDesc("create_time");
        }
        return wrapper;
    }


    @Override
    public IPage<StudyCoursewareDto> pageStudyCourseware(Page<StudyCoursewareDto> page, StudyCoursewareDto studyCoursewareDto) {
        QueryWrapper<StudyCoursewareEntity> wrapper = getWrapper(studyCoursewareDto);
        Page<StudyCoursewareEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<StudyCoursewareEntity> studyCoursewarePage = baseMapper.selectPage(pageEntity, wrapper);
        Page<StudyCoursewareDto> pageDto = new Page(studyCoursewarePage.getCurrent(), studyCoursewarePage.getSize(), studyCoursewarePage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(studyCoursewarePage.getRecords(), StudyCoursewareDto.class));
        return pageDto;
    }

    @Override
    public IPage<StudyCoursewareDto> pageStudyCoursewareExtends(Page<StudyCoursewareDto> page, StudyCoursewareDto studyCoursewareDto) {
        Map<String, Long> pageMap = BizCommonUtil.getPageParam(page);
        StudyCoursewareEntity studyCoursewareEntity = ConvertUtil.transformObj(studyCoursewareDto, StudyCoursewareEntity.class);
        List<StudyCoursewareEntity> studyCoursewareList = baseMapper.extendsList(pageMap, studyCoursewareEntity);
        Long total = baseMapper.extendsCount(studyCoursewareEntity);
        Page<StudyCoursewareDto> pageDto = new Page(page.getCurrent(), page.getSize(), total);
        pageDto.setRecords(ConvertUtil.transformObjList(studyCoursewareList, StudyCoursewareDto.class));
        return pageDto;
    }

    @Override
    public StudyCoursewareDto getByIdExtends(Long id) {
        StudyCoursewareEntity studyCoursewareEntity = baseMapper.getByIdExtends(id);
        return ConvertUtil.transformObj(studyCoursewareEntity, StudyCoursewareDto.class);
    }

    @Override
    public List<StudyCoursewareDto> listStudyCourseware(StudyCoursewareDto studyCoursewareDto) {
        QueryWrapper<StudyCoursewareEntity> wrapper = getWrapper(studyCoursewareDto);
        List<StudyCoursewareEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list, StudyCoursewareDto.class);
    }

    @Override
    public List<StudyCoursewareDto> selectBycourseId(Long courseId, Long chapterId) {
        List<StudyCoursewareDto> list = new ArrayList<>();
        if (courseId != null) {
            list = ConvertUtil.transformObjList(baseMapper.selectBycourseId(courseId, chapterId), StudyCoursewareDto.class);
        }
        return list;
    }

    @Override
    public List<StudyCoursewareDto> selectStudyListBycourseId(Long courseId, Long chapterId, Long memberId) {
        List<StudyCoursewareDto> list = new ArrayList<>();
        if (courseId != null) {
            list = ConvertUtil.transformObjList(baseMapper.selectStudyListBycourseId(courseId, chapterId, memberId), StudyCoursewareDto.class);
        }
        return list;
    }

    @Override
    public void savePdf2Png() {
        ConfigApiDto configApiDto = configApiService.getByBindCode("STUDY");
        if (configApiDto == null || StrUtil.isEmpty(configApiDto.getBindDetail())) {
            System.err.println(configApiDto);
            System.err.println("未配置pdf转图片本地路径");
            return;
        }
        JSONObject config = JSONUtil.parseObj(configApiDto.getBindDetail());
        String localPath = config.getStr("localPath");
        if (StrUtil.isEmpty(localPath)) {
            System.err.println("未配置pdf转图片本地路径");
            return;
        }
        List<StudyCoursewareEntity> toPngList = baseMapper.selectToPngList();

        for (StudyCoursewareEntity entity : toPngList) {

//            File file= PdfUtils.urlTransferMultipartFile(fileUrl);
//            System.err.println("文件路径:" + file.getPath());
            String url = JSONUtil.parseArray(entity.getCoursewareUrl()).getJSONObject(0).getStr("url");
            if (StrUtil.isNotEmpty(url)) {
                System.out.println(entity.getId() + "-" + entity.getCoursewareName() + ":已生成");
                pdfUtils.pdf2Image(url, localPath, 96, entity.getId(), "");

            } else {
                System.err.println("文件不存在");
            }
        }

    }

    @Override
    public List<String> findByCoursewareIds(ArrayList<Long> existIds) {
        return baseMapper.findByCoursewareIds(existIds);
    }

    @Override
    public void delByClassifyId(Long id) {
        if (id != null) {
            baseMapper.delByClassifyId(id);
        }
    }

    @Override
    public String coursewareUrlHandle(StudyCoursewareDto dto) {
        //新建标识
        StudyCoursewareEntity entityOld = null;
        Long id = IdWorker.getId();
        if (dto.getId() != null) {
            entityOld = this.getById(dto.getId());
        } else {
            dto.setId(id);
        }
        //如果上传类型是文件//一个文件为一个课件
        if (dto.getCoursewareType() == CoursewareTypeEnum.FILE.getCode()) {
            if (StrUtil.isEmpty(dto.getOriginUrl())) {
                throw new BizException("请上传文件");
            }
            JSONArray fileArr = JSONUtil.parseArray(dto.getOriginUrl());
            if (fileArr.size() != 1) {
                throw new BizException("请上传一个文件");
            }
            //编辑操作 且 课件并未发生改变
            if (entityOld != null && entityOld.getOriginUrl() != null && entityOld.getOriginUrl().equals(dto.getOriginUrl())) {
                this.updateById(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
                return "操作成功";
            } else {
                dto.setCoursewareUrl(dto.getOriginUrl());
            }
            JSONObject jsonObject = fileArr.getJSONObject(0);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            //课件类型转化
            String fileUrl = jsonObject.getStr("url");
            if (fileUrl.lastIndexOf(".jpg") != -1
                    || fileUrl.lastIndexOf(".png") != -1 || fileUrl.lastIndexOf(".webp") != -1) {
                dto.setNeedConver(0);

//                //文件地址
//                dto.setCoursewareUrl(jsonArray.toString());
            } else if (fileUrl.lastIndexOf(".pdf") != -1) {
                dto.setNeedConver(1);
                if (entityOld == null) {
                    this.save(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
                } else {
                    this.updateById(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
                }
//                dto.setId(id);
//                dto.setCoursewareUrl(jsonArray.toString());
                String url = JSONUtil.parseArray(dto.getCoursewareUrl()).getJSONObject(0).getStr("url");
                pdfUtils.taskPngAdd(url, 96, dto.getId(), jsonObject.getStr("name"));
                if (!pdfUtils.isTaskRunning()) {
                    pdfUtils.taskRun(); // 启动任务
                }
                return "操作成功";
            } else {
//                Long id = IdWorker.getId();
//                // 这里是文件转pdf
                dto.setNeedConver(1);
//                dto.setId(id);
                if (entityOld == null) {
                    this.save(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
                } else {
                    this.updateById(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
                }
                pdfUtils.taskAdd(fileUrl, jsonObject.getStr("name"), dto.getId());
                if (!pdfUtils.isTaskRunning()) {
                    pdfUtils.taskRun(); // 启动任务
                }
                return "操作成功";
            }
            //如果是视频
        } else if (dto.getCoursewareType() == CoursewareTypeEnum.VIDEO.getCode()) {
            if (StrUtil.isEmpty(dto.getCoursewareUrl())) {
                throw new BizException("请上传文件");
            }
            JSONArray fileArr = JSONUtil.parseArray(dto.getCoursewareUrl());
            if (fileArr.size() != 1) {
                throw new BizException("请上传一个文件");
            }
//            JSONObject item = fileArr.getJSONObject(0);
            //文件地址
//            dto.setCoursewareUrl(com.alibaba.fastjson.JSONObject.toJSONString(fileArr));
            dto.setNeedConver(0);
        } else {
            // 图文 不作操作
            dto.setNeedConver(0);
            System.err.println(dto);
        }
        if (entityOld == null) {
            this.save(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
        } else {
            this.updateById(ConvertUtil.transformObj(dto, StudyCoursewareEntity.class));
        }
        return "操作成功";
    }

    @Override
    @Async
    public void initConversionPdfToPng() {
        log.debug("初始未完成的任务PDF png");
        List<StudyCoursewareEntity> studyCoursewareEntityList = baseMapper.selectToPngOrPDFList();
        List<String> fileSuffixList = Arrays.stream(FileSuffixEnum.values()).map(item -> item.getName()).collect(Collectors.toList());
        studyCoursewareEntityList.forEach(item -> {
            JSONArray fileArr = JSONUtil.parseArray(item.getOriginUrl());
            JSONObject jsonObject = fileArr.getJSONObject(0);
            String fileUrl = jsonObject.getStr("url");
            if (fileUrl.lastIndexOf(FileSuffixEnum.PNG.getName()) !=-1 ||  fileUrl.lastIndexOf(FileSuffixEnum.JPG.getName()) !=-1 || fileUrl.lastIndexOf(FileSuffixEnum.WEBP.getName()) !=-1) {
                String url = JSONUtil.parseArray(item.getCoursewareUrl()).getJSONObject(0).getStr("url");
                pdfUtils.taskPngAdd(url, 96, item.getId(), jsonObject.getStr("name"));
            } else if (fileSuffixList.contains(fileUrl.substring(fileUrl.lastIndexOf(".")+1))){
                pdfUtils.taskAdd(fileUrl, jsonObject.getStr("name"), item.getId());
            }
        });
        if (!pdfUtils.isTaskRunning() && pdfUtils.getQueueSize() > 0) {
            pdfUtils.taskRun();
        }
    }
}

